import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Modal, Input, Button, Space, message, Spin, Tabs } from 'antd';
import { SaveOutlined, PlusOutlined, DeleteOutlined, BoldOutlined, BgColorsOutlined, AlignCenterOutlined } from '@ant-design/icons';
import { DocumentUtils } from '../utils/documentUtils';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { HotTable } from '@handsontable/react';
import 'handsontable/dist/handsontable.full.min.css';


const { TextArea } = Input;

const DocumentEditor = ({
    visible,
    fileUrl,
    fileName,
    onClose,
    onSave,
    baseUrl = 'http://localhost:3000'
}) => {
    const [loading, setLoading] = useState(false);
    const [fileType, setFileType] = useState(null);
    const [excelData, setExcelData] = useState({ Sheet1: [[]] });
    const [activeSheet, setActiveSheet] = useState('Sheet1');
    const [wordContent, setWordContent] = useState('');
    const hotRef = useRef();
    const [selectedRange, setSelectedRange] = useState(null);

    const loadDocument = useCallback(async () => {
        if (!fileUrl) return;

        setLoading(true);
        try {
            const fullUrl = `${baseUrl}${fileUrl}`;
            const fileType = DocumentUtils.getFileType(fileName);
            setFileType(fileType);

            const response = await fetch(fullUrl);
            const blob = await response.blob();
            const file = new File([blob], fileName, { type: blob.type });

            if (fileType === 'excel') {
                const data = await DocumentUtils.processExcelFile(file);
                // 支持多sheet
                const sheetsObj = {};
                data.sheetNames.forEach(name => {
                    sheetsObj[name] = data.sheets[name];
                });
                setExcelData(sheetsObj);
                setActiveSheet(data.sheetNames[0] || 'Sheet1');
            } else if (fileType === 'word') {
                const data = await DocumentUtils.processWordFile(file);
                setWordContent(data.content);
            }
        } catch (error) {
            console.error('文档加载失败:', error);
            message.error('文档加载失败');
        } finally {
            setLoading(false);
        }
    }, [fileUrl, fileName, baseUrl]);

    useEffect(() => {
        if (visible && fileUrl) {
            loadDocument();
        }
    }, [visible, fileUrl, loadDocument]);

    const handleSave = async () => {
        try {
            setLoading(true);

            if (fileType === 'excel') {
                await DocumentUtils.generateExcelFile(excelData, fileName);
            } else if (fileType === 'word') {
                await DocumentUtils.generateWordFile(wordContent, fileName);
            }

            message.success('文档保存成功');
            if (onSave) {
                onSave();
            }
            onClose();
        } catch (error) {
            console.error('保存失败:', error);
            message.error('保存失败');
        } finally {
            setLoading(false);
        }
    };

    // Excel样式工具栏操作
    const setBold = () => {
        const hot = hotRef.current.hotInstance;
        if (!selectedRange) return;
        const [rowStart, colStart, rowEnd, colEnd] = selectedRange;
        for (let row = rowStart; row <= rowEnd; row++) {
            for (let col = colStart; col <= colEnd; col++) {
                hot.setCellMeta(row, col, 'className', (hot.getCellMeta(row, col).className || '') + ' htBold');
            }
        }
        hot.render();
    };

    const setBgYellow = () => {
        const hot = hotRef.current.hotInstance;
        if (!selectedRange) return;
        const [rowStart, colStart, rowEnd, colEnd] = selectedRange;
        for (let row = rowStart; row <= rowEnd; row++) {
            for (let col = colStart; col <= colEnd; col++) {
                if (row >= 0 && col >= 0) {
                    hot.setCellMeta(row, col, 'className', (hot.getCellMeta(row, col).className || '') + ' bgYellow');
                }
            }
        }
        hot.render();
    };

    const setAlignCenter = () => {
        const hot = hotRef.current.hotInstance;
        if (!selectedRange) return;
        const [rowStart, colStart, rowEnd, colEnd] = selectedRange;
        for (let row = rowStart; row <= rowEnd; row++) {
            for (let col = colStart; col <= colEnd; col++) {
                hot.setCellMeta(row, col, 'className', (hot.getCellMeta(row, col).className || '') + ' htCenter');
            }
        }
        hot.render();
    };

    // 添加新Sheet
    const handleAddSheet = () => {
        let idx = 1;
        let newSheetName = '';
        do {
            newSheetName = `Sheet${Object.keys(excelData).length + idx}`;
            idx++;
        } while (excelData[newSheetName]);
        setExcelData({ ...excelData, [newSheetName]: [['']] });
        setActiveSheet(newSheetName);
    };

    // 插入行
    const handleAddRow = () => {
        const hot = hotRef.current.hotInstance;
        const selected = hot.getSelected();
        const sheet = activeSheet;
        let insertIndex = 0;
        if (selected && selected.length > 0) {
            insertIndex = selected[0][0]; // 在选中行前插入
        } else {
            insertIndex = excelData[sheet].length; // 末尾插入
        }
        const newRow = new Array(excelData[sheet][0]?.length || 1).fill('');
        const newSheetData = [...excelData[sheet]];
        newSheetData.splice(insertIndex, 0, newRow);
        setExcelData({ ...excelData, [sheet]: newSheetData });
        setTimeout(() => {
            const hot = hotRef.current?.hotInstance;
            if (hot && !hot.isDestroyed && hot.selectCell) {
                hot.selectCell(insertIndex, 0);
            }
        }, 100);
    };

    // 插入列
    const handleAddCol = () => {
        const hot = hotRef.current.hotInstance;
        const selected = hot.getSelected();
        const sheet = activeSheet;
        let insertIndex = 0;
        if (selected && selected.length > 0) {
            insertIndex = selected[0][1]; // 在选中列前插入
        } else {
            insertIndex = excelData[sheet][0]?.length || 0; // 末尾插入
        }
        const newSheetData = excelData[sheet].map(row => {
            const newRow = [...row];
            newRow.splice(insertIndex, 0, '');
            return newRow;
        });
        setExcelData({ ...excelData, [sheet]: newSheetData });
        setTimeout(() => {
            const hot = hotRef.current?.hotInstance;
            if (hot && !hot.isDestroyed && hot.selectCell) {
                hot.selectCell(0, insertIndex);
            }
        }, 100);
    };

    // 删除行
    const handleDeleteRow = () => {
        const hot = hotRef.current.hotInstance;
        const sheet = activeSheet;
        if (!selectedRange) {
            message.info('没有选中任何区域');
            return;
        }
        const [rowStart, , rowEnd] = selectedRange;
        const start = Math.min(rowStart, rowEnd);
        const end = Math.max(rowStart, rowEnd);
        const newSheetData = [...excelData[sheet]];
        newSheetData.splice(start, end - start + 1);
        setExcelData({ ...excelData, [sheet]: newSheetData });
        setTimeout(() => {
            const hot = hotRef.current?.hotInstance;
            if (hot && !hot.isDestroyed && hot.selectCell) {
                hot.selectCell(start > 0 ? start - 1 : 0, 0);
            }
        }, 100);
    };

    // 删除列
    const handleDeleteCol = () => {
        const hot = hotRef.current.hotInstance;
        const sheet = activeSheet;
        if (!selectedRange) {
            message.info('没有选中任何区域');
            return;
        }
        // 注意：列的选区是 [rowStart, colStart, rowEnd, colEnd]
        const [, colStart, , colEnd] = selectedRange;
        const start = Math.min(colStart, colEnd);
        const end = Math.max(colStart, colEnd);
        const newSheetData = excelData[sheet].map(row => {
            const newRow = [...row];
            newRow.splice(start, end - start + 1);
            return newRow;
        });
        setExcelData({ ...excelData, [sheet]: newSheetData });
        setTimeout(() => {
            const hot = hotRef.current?.hotInstance;
            if (hot && !hot.isDestroyed && hot.selectCell) {
                hot.selectCell(0, start > 0 ? start - 1 : 0);
            }
        }, 100);
    };
    const renderExcelEditor = () => (
        <>
            <Space style={{ marginBottom: 8 }}>
                <Button icon={<BoldOutlined />} onClick={setBold}>加粗</Button>
                <Button icon={<BgColorsOutlined />} onClick={setBgYellow}>黄色背景</Button>
                <Button icon={<AlignCenterOutlined />} onClick={setAlignCenter}>居中</Button>
                <Button icon={<PlusOutlined />} onClick={handleAddRow}>插入行</Button>
                <Button icon={<PlusOutlined />} onClick={handleAddCol}>插入列</Button>
                <Button icon={<DeleteOutlined />} onClick={handleDeleteRow}>删除行</Button>
                <Button icon={<DeleteOutlined />} onClick={handleDeleteCol}>删除列</Button>
                <Button icon={<PlusOutlined />} onClick={handleAddSheet}>添加工作表</Button>
                <Tabs
                    activeKey={activeSheet}
                    onChange={setActiveSheet}
                    type="card"
                    style={{ display: 'inline-block', marginLeft: 16 }}
                >
                    {Object.keys(excelData).map(sheet => (
                        <Tabs.TabPane tab={sheet} key={sheet} />
                    ))}
                </Tabs>
            </Space>
            <HotTable
                ref={hotRef}
                data={excelData[activeSheet]}
                colHeaders={true}
                rowHeaders={true}
                width="100%"
                height="400"
                colWidths={120}
                licenseKey="non-commercial-and-evaluation"
                contextMenu={['row_above', 'row_below', 'col_left', 'col_right', 'remove_row', 'remove_col', '---------', 'undo', 'redo', 'make_read_only', 'alignment', 'borders', 'mergeCells', 'copy', 'cut', 'paste', 'clear_column']}
                manualColumnResize={true}
                manualRowResize={true}
                mergeCells={true}
                afterChange={(changes, source) => {
                    if (source === 'edit' && changes) {
                        console.log('单元格编辑:', changes);
                        setExcelData({ ...excelData, [activeSheet]: [...excelData[activeSheet]] });
                    }
                }}
                afterSelection={(row, col, row2, col2) => {
                    setSelectedRange([row, col, row2, col2]);
                }}
            />
        </>
    );

    const renderWordEditor = () => (
        <ReactQuill
            value={wordContent}
            onChange={setWordContent}
            style={{ height: 400 }}
            modules={{
                toolbar: [
                    [{ 'font': [] }, { 'size': [] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'align': [] }],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    ['clean']
                ]
            }}
        />
    );

    return (
        <Modal
            title={`编辑文档 - ${fileName}`}
            open={visible}
            onCancel={onClose}
            width="90%"
            footer={[
                <Button key="cancel" onClick={onClose}>
                    取消
                </Button>,
                <Button
                    key="save"
                    type="primary"
                    icon={<SaveOutlined />}
                    loading={loading}
                    onClick={handleSave}
                >
                    保存
                </Button>
            ]}
        >
            <Spin spinning={loading}>
                {fileType === 'excel' && renderExcelEditor()}
                {fileType === 'word' && renderWordEditor()}
                {!fileType && <div>不支持的文件类型</div>}
            </Spin>
        </Modal>
    );
};

export default DocumentEditor;
